package org.jeecg.modules.userFormula.controller;

import java.io.IOException;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xkcoding.http.HttpUtil;
import com.xkcoding.http.config.HttpConfig;
import org.jeecg.modules.userFormula.vo.CalcFormulaParam;
import org.jeecg.modules.userFormula.vo.UserFormulaPage;
import org.jeecg.modules.util.HttpClientUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.userFormula.entity.UserFormulaDetail;
import org.jeecg.modules.userFormula.entity.UserFormulaPortion;
import org.jeecg.modules.userFormula.entity.UserFormula;
import org.jeecg.modules.userFormula.service.IUserFormulaService;
import org.jeecg.modules.userFormula.service.IUserFormulaDetailService;
import org.jeecg.modules.userFormula.service.IUserFormulaPortionService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 算法库
 * @Author: jeecg-boot
 * @Date: 2023-02-23
 * @Version: V1.0
 */
@Api(tags = "算法库")
@RestController
@RequestMapping("/userFormula/userFormula")
@Slf4j
public class UserFormulaController {
    @Autowired
    private IUserFormulaService userFormulaService;
    @Autowired
    private IUserFormulaDetailService userFormulaDetailService;
    @Autowired
    private IUserFormulaPortionService userFormulaPortionService;

    @Value("${zfservice.url}")
    private String zfserviceUrl;

    /**
     * 分页列表查询
     *
     * @param userFormula
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "算法库-分页列表查询")
    @ApiOperation(value = "算法库-分页列表查询", notes = "算法库-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<UserFormula>> queryPageList(UserFormula userFormula,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {
        QueryWrapper<UserFormula> queryWrapper = QueryGenerator.initQueryWrapper(userFormula, req.getParameterMap());
        Page<UserFormula> page = new Page<UserFormula>(pageNo, pageSize);
        IPage<UserFormula> pageList = userFormulaService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param
     * @return
     */
    @AutoLog(value = "算法库-添加")
    @ApiOperation(value = "算法库-添加", notes = "算法库-添加")
    //@RequiresPermissions("userFormula:user_formula:add")
    @PostMapping(value = "/add")
    public Result<UserFormula> add(@RequestBody UserFormula userFormula) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        LambdaQueryWrapper<UserFormula> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserFormula::getFormulaName, userFormula.getFormulaName());
        long count = userFormulaService.count(queryWrapper);
        if (count > 0) {
            return Result.error("算法名称已存在！");
        }
        userFormula.setId(null);
        userFormula.setModifyDate(new Date());
        userFormula.setUserId(user.getUsername());
        userFormulaService.save(userFormula);
        return Result.OK("添加成功！", userFormula);
    }

    @AutoLog(value = "引用函数-添加")
    @ApiOperation(value = "引用函数-添加", notes = "引用函数-添加")
    @PostMapping(value = "/addFormulaDetail")
    public Result<UserFormulaDetail> addFormulaDetail(@RequestBody UserFormulaDetail userFormulaDetail) {
        LambdaQueryWrapper<UserFormulaDetail> queryWrapper = new LambdaQueryWrapper<>();
        if (userFormulaDetail.getId() != null && userFormulaDetail.getId() > 0) {
            queryWrapper.ne(UserFormulaDetail::getId, userFormulaDetail.getId());
            queryWrapper.eq(UserFormulaDetail::getFunId, userFormulaDetail.getFunId());
            queryWrapper.eq(UserFormulaDetail::getFormulaId, userFormulaDetail.getFormulaId());
            long count = userFormulaDetailService.count(queryWrapper);
            if (count > 0) {
                return Result.error("函数标识已存在！");
            }
            userFormulaDetailService.updateById(userFormulaDetail);
        } else {
            queryWrapper.eq(UserFormulaDetail::getFunId, userFormulaDetail.getFunId());
            queryWrapper.eq(UserFormulaDetail::getFormulaId, userFormulaDetail.getFormulaId());
            long count = userFormulaDetailService.count(queryWrapper);
            if (count > 0) {
                return Result.error("函数标识已存在！");
            }
            userFormulaDetail.setId(null);
            userFormulaDetailService.save(userFormulaDetail);
        }
        return Result.OK("操作成功！", userFormulaDetail);
    }


    @AutoLog(value = "引用函数-删除")
    @ApiOperation(value = "引用函数-删除", notes = "引用函数-删除")
    @DeleteMapping(value = "/deleteFormulaDetail")
    public Result<String> deleteFormulaDetail(@RequestParam(name = "detailId", required = true) String detailId) {
        userFormulaDetailService.removeById(detailId);
        return Result.OK("删除成功!");
    }


    @AutoLog(value = "运行结果区间设置-保存")
    @ApiOperation(value = "运行结果区间设置-保存", notes = "运行结果区间设置-保存")
    @PostMapping(value = "/savePortion")
    public Result<UserFormulaPortion> savePortion(@RequestBody List<UserFormulaPortion> userFormulaPortionList) {
        QueryWrapper<UserFormulaPortion> qw = new QueryWrapper();
        qw.lambda().eq(true, UserFormulaPortion::getFormulaId, userFormulaPortionList.get(0).getFormulaId());
        userFormulaPortionService.remove(qw);
        for (int i = 0; i < userFormulaPortionList.size(); i++) {
            userFormulaPortionList.get(i).setId(null);
            userFormulaPortionService.save(userFormulaPortionList.get(i));
        }
        return Result.OK("添加成功！");
    }

    @AutoLog(value = "运行结果区间设置-保存")
    @ApiOperation(value = "运行结果区间设置-保存", notes = "运行结果区间设置-保存")
    @PostMapping(value = "/addPortion")
    public Result<UserFormulaPortion> addPortion(@RequestBody UserFormulaPortion userFormulaPortion) {
        userFormulaPortionService.save(userFormulaPortion);
        return Result.OK("添加成功！",userFormulaPortion);
    }

    @AutoLog(value = "运行结果区间设置-通过id删除")
    @ApiOperation(value = "运行结果区间设置-通过id删除", notes = "运行结果区间设置-通过id删除")
    @DeleteMapping(value = "/deletePortion")
    public Result<String> deletePortion(@RequestParam(name = "id", required = true) String id) {
        userFormulaPortionService.removeById(id);
        return Result.OK("删除成功!");
    }

    @AutoLog(value = "运行结果区间设置-编辑")
    @ApiOperation(value = "运行结果区间设置-编辑", notes = "运行结果区间设置-编辑")
    @RequestMapping(value = "/editPortion", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<UserFormulaPortion> editPortion(@RequestBody UserFormulaPortion userFormulaPortion) {
        UserFormulaPortion userFormulaPortionEntity = userFormulaPortionService.getById(userFormulaPortion.getId());
        if (userFormulaPortionEntity == null) {
            return Result.error("未找到对应数据");
        }
        userFormulaPortionService.updateById(userFormulaPortion);
        return Result.OK("编辑成功!",userFormulaPortion);
    }

    @AutoLog(value = "引用函数-函数试算")
    @ApiOperation(value = "引用函数-函数试算", notes = "引用函数-函数试算")
    @PostMapping(value = "/tryFormulaDetail")
    public Result<Object> tryFormulaDetail(@RequestParam(name = "dataSoltId", required = true) String dataSoltId, @RequestParam(name = "formulaDetailId", required = true) String formulaDetailId,
                                           @RequestParam(name = "calcDate", required = true) String calcDate) {
        Map<String, String> paramsMap = new HashMap<>();
        paramsMap.put("slot_no", dataSoltId);
        UserFormulaDetail userFormulaDetail = userFormulaDetailService.getById(formulaDetailId);
        paramsMap.put("fun_type", userFormulaDetail.getFunType());
        paramsMap.put("fun_para", userFormulaDetail.getFunPara());
        paramsMap.put("calc_date", calcDate);
        try {
            String url = zfserviceUrl + "/formula/calc_function";
            JSONObject object = HttpClientUtil.sendGet(url, paramsMap);
            if (object == null) {
                return Result.error("试算失败");
            }
            if (object.get("code") != null && Integer.parseInt(object.get("code").toString()) == 0) {
                return Result.OK(object.get("data"));
            } else {
                if (object.containsKey("message") && object.get("message") != null) {
                    return Result.error(object.get("message").toString());
                } else {
                    return Result.error("试算失败");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
            return Result.error("试算失败，请联系管理员");
        }
    }

    /**
     * 编辑
     *
     * @param userFormula
     * @return
     */
    @AutoLog(value = "算法库-编辑")
    @ApiOperation(value = "算法库-编辑", notes = "算法库-编辑")
    //@RequiresPermissions("userFormula:user_formula:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<UserFormula> edit(@RequestBody UserFormula userFormula) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        UserFormula userFormulaEntity = userFormulaService.getById(userFormula.getId());
        if (userFormulaEntity == null) {
            return Result.error("未找到对应数据");
        }
        LambdaQueryWrapper<UserFormula> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserFormula::getFormulaName, userFormula.getFormulaName());
        queryWrapper.ne(UserFormula::getId, userFormula.getId());
        long count = userFormulaService.count(queryWrapper);
        if (count > 0) {
            return Result.error("算法名称已存在！");
        }
        userFormula.setModifyDate(new Date());
        userFormula.setUserId(user.getUsername());
        userFormulaService.updateById(userFormula);
        return Result.OK("编辑成功!",userFormula);
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "算法库-通过id删除")
    @ApiOperation(value = "算法库-通过id删除", notes = "算法库-通过id删除")
    //@RequiresPermissions("userFormula:user_formula:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        userFormulaService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "算法库-批量删除")
    @ApiOperation(value = "算法库-批量删除", notes = "算法库-批量删除")
    //@RequiresPermissions("userFormula:user_formula:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.userFormulaService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "算法库-通过id查询")
    @ApiOperation(value = "算法库-通过id查询", notes = "算法库-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<UserFormula> queryById(@RequestParam(name = "id", required = true) String id) {
        UserFormula userFormula = userFormulaService.getById(id);
        if (userFormula == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(userFormula);

    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "引用函数通过主表ID查询")
    @ApiOperation(value = "引用函数主表ID查询", notes = "引用函数-通主表ID查询")
    @GetMapping(value = "/queryUserFormulaDetailByMainId")
    public Result<List<UserFormulaDetail>> queryUserFormulaDetailListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<UserFormulaDetail> userFormulaDetailList = userFormulaDetailService.selectByMainId(id);
        return Result.OK(userFormulaDetailList);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "运行结果区间设置通过主表ID查询")
    @ApiOperation(value = "运行结果区间设置主表ID查询", notes = "运行结果区间设置-通主表ID查询")
    @GetMapping(value = "/queryUserFormulaPortionByMainId")
    public Result<List<UserFormulaPortion>> queryUserFormulaPortionListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<UserFormulaPortion> userFormulaPortionList = userFormulaPortionService.selectByMainId(id);
        return Result.OK(userFormulaPortionList);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param userFormula
     */
    //@RequiresPermissions("userFormula:user_formula:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, UserFormula userFormula) {
        // Step.1 组装查询条件查询数据
        QueryWrapper<UserFormula> queryWrapper = QueryGenerator.initQueryWrapper(userFormula, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        //配置选中数据查询条件
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            queryWrapper.in("id", selectionList);
        }
        //Step.2 获取导出数据
        List<UserFormula> userFormulaList = userFormulaService.list(queryWrapper);

        // Step.3 组装pageList
        List<UserFormulaPage> pageList = new ArrayList<UserFormulaPage>();
        for (UserFormula main : userFormulaList) {
            UserFormulaPage vo = new UserFormulaPage();
            BeanUtils.copyProperties(main, vo);
            List<UserFormulaDetail> userFormulaDetailList = userFormulaDetailService.selectByMainId(main.getId().toString());
            vo.setUserFormulaDetailList(userFormulaDetailList);
            List<UserFormulaPortion> userFormulaPortionList = userFormulaPortionService.selectByMainId(main.getId().toString());
            vo.setUserFormulaPortionList(userFormulaPortionList);
            pageList.add(vo);
        }

        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "算法库列表");
        mv.addObject(NormalExcelConstants.CLASS, UserFormulaPage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("算法库数据", "导出人:" + sysUser.getRealname(), "算法库"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresPermissions("userFormula:user_formula:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<UserFormulaPage> list = ExcelImportUtil.importExcel(file.getInputStream(), UserFormulaPage.class, params);
                for (UserFormulaPage page : list) {
                    UserFormula po = new UserFormula();
                    BeanUtils.copyProperties(page, po);
                    userFormulaService.saveMain(po, page.getUserFormulaDetailList(), page.getUserFormulaPortionList());
                }
                return Result.OK("文件导入成功！数据行数:" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.OK("文件导入失败！");
    }


    @AutoLog(value = "引用函数-函数试算")
    @ApiOperation(value = "引用函数-函数试算", notes = "引用函数-函数试算")
    @PostMapping(value = "/tryFormula")
    public Result<Object> tryFormula(@RequestBody CalcFormulaParam calcFormulaParam) {
        Map<String, String> paramsMap = new HashMap<>();
        paramsMap.put("slots", calcFormulaParam.getDataSoltIds());
        paramsMap.put("formula_id", calcFormulaParam.getFormulaId().toString());
        paramsMap.put("calc_date", calcFormulaParam.getCalcDate());
        try {
            String url = zfserviceUrl + "/formula/calc_formula";
            JSONObject object = HttpClientUtil.sendGet(url, paramsMap);
            if (object == null) {
                return Result.error("试算失败");
            }
            if (object.get("code") != null && Integer.parseInt(object.get("code").toString()) == 0) {
                return Result.OK(object.get("data"));
            } else {
                if (object.containsKey("message") && object.get("message") != null) {
                    return Result.error(object.get("message").toString());
                } else {
                    return Result.error("试算失败");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
            return Result.error("试算失败，请联系管理员");
        }
    }
}
